import React, { Component } from "react";
import { connect } from "react-redux";
import Upload from "./upload.UI";
import BaseService from "share/base.service";
import constants from "share/constants";
import config from "config";
import { handleUploadOptions } from "share/utils";

function mapStateToProps(state) {
  return {
    authToken: state.main.authToken,
    loginCompany: state.login.loginCompany,
  };
}

@connect(mapStateToProps)
class FileUpload extends Component {
  state = {
    attachmentTypesAry: [],
    attachmentTypes: "",
    acceptTypes: "",
  };

  constructor(props) {
    super(props);
    this.initExtraPrompt();
  }

  getMaxFileSize = () => {
    // 处理相关业务逻辑
    let { loginCompany, fileSize = 10 } = this.props;
    if (loginCompany.maximumFileSize && !isNaN(loginCompany.maximumFileSize)) {
      return loginCompany.maximumFileSize;
    }
    return this.props.fileSize;
  };

  initExtraPrompt = () => {
    BaseService.getAttachmentType().then((data) => {
      let types = data.types || "";
      let formats = data.formats || [];
      this.allowedTypes = types;
      let acceptTypes = formats.map((type) => `.${type}`);
      this.setState({
        attachmentTypesAry: formats,
        attachmentTypes: formats.join("/"),
        acceptTypes: acceptTypes.join(","),
      });
    });
  };

  getPropAccept = () => {
    let { isShowExtraPrompt, accept = "", mode } = this.props;
    let { acceptTypes, attachmentTypesAry } = this.state;
    let isDingTalkSSO = sessionStorage.getItem("isDingTalkSSO");
    let isWechatSSO = sessionStorage.getItem("isWechatSSO");
    accept = accept
      .split(",")
      .filter((type) => {
        type = type.toLowerCase();
        if (type.startsWith(".")) {
          type = type.substring(1);
        }
        if (type === "image/*" && this.allowedTypes && this.allowedTypes.includes("IMAGE")) {
          return true;
        }
        if (type !== "image/*" && type.includes("/")) {
          let typeAry = type.split("/");
          type = typeAry[typeAry.length - 1];
        }
        return attachmentTypesAry.includes(type);
      })
      .join(",");
    let acceptProps =
      isDingTalkSSO === "true" || isWechatSSO === "true"
        ? ""
        : isShowExtraPrompt && acceptTypes
        ? acceptTypes
        : accept
        ? accept
        : mode === "image"
        ? "image/*"
        : accept;
    return acceptProps;
  };

  getPropData = () => {
    if (window.ISIE9) {
      return {
        ...this.props.data,
        access_token: this.props.authToken.token,
      };
    }
    return this.props.data;
  };

  getPropUploadUrl = () => {};

  getPropHeaders = () => {
    if (window.ISIE9) {
      return {};
    }
    return {
      Authorization: "Bearer " + this.props.authToken.access_token,
    };
  };

  getPropAttachmentTypes = () => {
    return this.state.attachmentTypes;
  };

  render() {
    let headers = this.getPropHeaders();
    let [uploadHeaders, uploadUrl] = handleUploadOptions(headers, this.props.uploadUrl);
    let props = Object.assign({}, this.props, {
      uploadUrl: uploadUrl,
      headers: uploadHeaders,
      accept: this.getPropAccept(),
      fileSize: this.getMaxFileSize(),
      attachmentTypes: this.getPropAttachmentTypes(),
      defaultFileList: this.props.defaultFileList || this.props.value,
      data: this.getPropData(),
    });
    return <Upload {...props} />;
  }
}

FileUpload.propTypes = {
  mode: React.PropTypes.string, //上传按钮模式 ['file', 'image']
  uploadUrl: React.PropTypes.string, //上传URL
  attachmentType: React.PropTypes.string.isRequired, //附件类型
  attachmentTypes: React.PropTypes.array, //可上传的文件类型
  defaultFileList: React.PropTypes.array, //默认上传的文件列表
  onChange: React.PropTypes.func, //上传成功后的回调
  maxNum: React.PropTypes.number, //最大上传文件的数量
  placeHolder: React.PropTypes.string, //控件配置的提示文案
  fileType: React.PropTypes.array, //上传文件的类型
  fileSize: React.PropTypes.number, //上传文件的大小
  isShowDefault: React.PropTypes.bool, //是否要进行回显，是否一直允许从父组件接受变化的图片列表
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool, //是否显示最多上传多少图片
  data: React.PropTypes.object, //上传接口的参数
  handleDelete: React.PropTypes.func, //删除附件的回调
  handlePreViewCallBack: React.PropTypes.func, //附件预览回调
  accept: React.PropTypes.string, //附件只接受选择的类型
  isShowExtraPrompt: React.PropTypes.bool, //是否展示安全配置中支持上传的附件类型文案
  isUploading: React.PropTypes.func, //附件是否正在上传中
  readOnly: React.PropTypes.bool,
  multiple: React.PropTypes.bool, // 是否支持多选
  responseFilePath: React.PropTypes.string, // file的path e.g : "data.body.file"
};

FileUpload.defaultProps = {
  mode: `file`,
  uploadUrl: `${config.baseUrl}/api/upload/attachment`,
  attachmentType: "OTHER",
  defaultFileList: [],
  onChange: () => {},
  maxNum: 9,
  placeHolder: "",
  isShowDefault: false,
  disabled: false,
  showMaxNum: false,
  isPreViewCallBack: false,
  readOnly: false,
  handleDelete: () => {
    return true;
  },
  showFileName: true,
  accept: constants.acceptFileTypes,
  isShowExtraPrompt: false,
  isUploading: () => {},
  attachmentTypes: [],
  multiple: true,
  fileSize: 10,
  responseFilePath: "",
};

export default FileUpload;
